import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';

/**
 * 统一的配置接口，与config.yaml结构对应
 */
export interface Config {
    global: {
        logDir: string;
        dataLimit: number;
        enableRealtime: boolean;
        useLatestKline?: boolean;
        updateCount?: number;
        getTradingAdvice?: boolean;
        api?: {
            baseUrl?: string;
            proxy?: string;
            timeout?: number;
        };
    };
    instruments: Array<{
        instId: string;
        indicators: Array<{
            type: string;
            configs: Array<{
                bar: string;
                period?: number;
                fastPeriod?: number;
                slowPeriod?: number;
                signalPeriod?: number;
                stdDev?: number;
                [key: string]: any;
            }>;
        }>;
    }>;
}

/**
 * 配置服务类
 * 采用单例模式，负责读取和提供全局配置
 */
class ConfigService {
    private static instance: ConfigService;
    private readonly config: Config;

    private constructor() {
        const configPath = path.resolve(process.cwd(), 'configs/config.yaml');
        if (!fs.existsSync(configPath)) {
            throw new Error(`配置文件不存在: ${configPath}`);
        }
        const configContent = fs.readFileSync(configPath, 'utf8');
        this.config = yaml.load(configContent) as Config;
    }

    /**
     * 获取ConfigService的单例
     */
    public static getInstance(): ConfigService {
        if (!ConfigService.instance) {
            ConfigService.instance = new ConfigService();
        }
        return ConfigService.instance;
    }

    /**
     * 获取完整的配置对象
     */
    public getFullConfig(): Config {
        return this.config;
    }

    /**
     * 获取API相关的配置
     */
    public getApiConfig() {
        return this.config.global.api;
    }

    /**
     * 获取代理配置
     */
    public getProxy(): string | undefined | null {
        return this.config.global.api?.proxy;
    }
}

// 导出单例
export const configService = ConfigService.getInstance(); 